package system_storage_service

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *Storage) DeleteObject(ctx context.Context, object *model.SystemObject) errors.Error {
	if nil == object {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_GE.S_GE.DO_CT.132937 object is nil")

		return errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.145809", "异常的传入参数")
	}

	if model.SystemObjectStatusUploading == *object.Status {
		return errors.New(errors.ErrorTypeInvalidRequest, "ISS_GE.S_GE.DO_CT.185822", "对象上传中，无法删除")
	}

	if model.SystemObjectStatusDeleted == *object.Status {
		return nil
	}

	provider, err := cls.GetProviderByName(*object.Provider)
	if err != nil {
		return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.375938", "获取存储提供商失败"))
	}

	md5, sha1, sha256, err := provider.GetObjectHash(ctx, *object.Filepath)
	if err != nil {
		if err.IsType(errors.ErrorTypeRecordNotFound) {
			object.Status = pointer.New(model.SystemObjectStatusDeleted)
			if err := cls.object.SaveSystemObject(ctx, object); err != nil {
				return err.Relation(errors.New(errors.ErrorTypeServerInternalError, "ISS_GE.S_GE.DO_CT.325933", "保存对象失败"))
			}

			return nil
		}

		return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.334747", "获取对象哈希值失败"))
	}

	if md5 != *object.Md5 || sha1 != *object.Sha1 || sha256 != *object.Sha256 {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_GE.S_GE.DO_CT.464846 删除对象失败，对象哈希值不匹配(存储桶-数据库): md5 %s - %s, sha1 %s - %s, sha256 %s - %s", md5, *object.Md5, sha1, *object.Sha1, sha256, *object.Sha256)

		return errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.343559", "对象哈希值不匹配")
	}

	if err := provider.DeleteObject(ctx, *object.Filepath); err != nil {
		if err.IsType(errors.ErrorTypeRecordNotFound) {
			object.Status = pointer.New(model.SystemObjectStatusDeleted)
			if err := cls.object.SaveSystemObject(ctx, object); err != nil {
				return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.325933", "保存对象失败"))
			}

			return nil
		}

		return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.415943", "删除对象失败"))
	}

	object.Status = pointer.New(model.SystemObjectStatusDeleted)
	if err := cls.object.SaveSystemObject(ctx, object); err != nil {
		return err.Relation(errors.ErrorServerInternalError("ISS_GE.S_GE.DO_CT.325933", "保存对象失败"))
	}

	return nil
}
